package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.PraiseDao;
import com.leoman.entity.Praise;
import com.leoman.service.PraiseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * PraiseServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 4:00.
 */
@Service
public class PraiseServiceImpl implements PraiseService {

    @Autowired
    private PraiseDao praiseDao;

    @Override
    public List<Praise> findAll() {
        return praiseDao.findAll();
    }

    @Override
    public Page<Praise> find(int pageNum, int pageSize) {
        return praiseDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Praise> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Praise getById(int id) {
        return praiseDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        praiseDao.delete(id);
    }

    @Override
    public Praise create(Praise praise) {
        return praiseDao.save(praise);
    }

    @Override
    public Praise update(Praise praise) {
        return praiseDao.save(praise);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public List<Praise> findListBySourceIdAndType(Integer sourceId, Integer type) {
        return praiseDao.findListBySourceIdAndType(sourceId, type);
    }

    @Override
    public Integer deleteAllInfo(Integer sourceId, Integer sourceType) {
        try {
            List<Praise> praiseList = praiseDao.findListBySourceIdAndType(sourceId, sourceType);

            for (Praise praise : praiseList) {
                praiseDao.delete(praise);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}